package com.hhf.riceshopping.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.hhf.common.constant.ProductConstant;
import com.hhf.common.to.SkuHasStockVo;
import com.hhf.common.to.SkuReductionTo;
import com.hhf.common.to.SpuBoundTo;
import com.hhf.common.to.es.SkuEsModel;
import com.hhf.common.utils.R;
import com.hhf.riceshopping.product.entity.*;
import com.hhf.riceshopping.product.feign.CouponFeignService;
import com.hhf.riceshopping.product.feign.SearchFeignService;
import com.hhf.riceshopping.product.feign.WareFeignService;
import com.hhf.riceshopping.product.service.*;
import com.hhf.riceshopping.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.common.utils.PageUtils;
import com.hhf.common.utils.Query;

import com.hhf.riceshopping.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * //TODO 高级部分完善
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2、保存spu的描述图片pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        /**
         * 第一个参数：哪个商品的图片
         * 第二个参数：具体图片
         */
        imagesService.saveImages(infoEntity.getId(),images);

        //4、保存spu的基本属性信息-规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            //查询属性的名字
            AttrEntity id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        //远程调用riceshopping-conpon服务来保存spu对应的积分信息，sms_spu_bounds（积分表）
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        //spuid 成长积分，购物积分
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() !=0){ //出现异常
            log.error("远程保存spu积分信息失败");
        }

        //5、保存当前spu对应的所有sku信息
        //5.1 保存sku的基本信息pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (skus!=null&& skus.size()>0){

            skus.forEach(item->{
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();//自增主键
                //5.2 sku的图片信息 pms_sku_images
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);;
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                    //TODO 没有图片：路径的无需保存,要进行过滤处理
                }).filter(entity->{
                    //返回true就是需要，返回false就需要被过滤掉
                    //过滤条件是ImgUrl是要有图片路径的，如果没有就过滤掉
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());

                skuImagesService.saveBatch(imagesEntities);

                //5.3 sku的销售属性信息  pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5.4 sku的优惠，满减等信息 需要
                // 跨库 gulimall_sms查询sms_sku_ladder（打折表）和sms_sku_full_reduction（满减表）
                // 以及sms_member_price（会员价格表）
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                //满件是0的和满减是大于0的，才需要发远程调用
                if (skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() !=0){ //出现异常
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }
    }

    //1、保存spu基本信息 pms_spu_info
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    //spu检索
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
                wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    /**
     * 商品上架
     * @param spuId  这个spu旗下有非常多的sku
     */
    @Override
    public void up(Long spuId) {
        //1.查出当前spu对应的所有sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        //收集到所有sku的id
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //查询出当前sku所有的可以被用来检索的规格属性信息
        //先查询出当前spu对应所有的属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);
        //再挑出所有能够检索属性的信息
        List<Long> attrIds = baseAttrs.stream().map(attr -> {  //先收集到所有属性的id
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //再根据收集到的属性id去attr表里边挑选出id在对应的集合里边并且检索类型是1的，1代表的就是检索属性
        List<Long> searchAttrIds = attrService.selectSearchAttrsIds(attrIds);  //查询出所有对应的检索属性
        //从baseAttrs这个集合里边过滤出只属于searchAttrIds集合的内容
        //为了方便判断期间，把searchAttrIds转为set，然后判断这个set里边有没有这个item.getAttrId();就容易多了
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {   //从idSet当中获取真正的信息
            //拿到当前正在遍历的元素id，这个元素id在searchAttrIds这个里边的就最好了
            return idSet.contains(item.getAttrId());  //如果说包含就返回true  就是说明要用的元素
        }).map(item -> {
            //拿到过滤掉的属于检索的数据进行一个封装，封装成attrs的集合
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        //TODO 发送远程调用库存系统查询是否有库存  利用sku的id来统一查询库存信息
        Map<Long, Boolean> stockMap = null;
        try {
            //如果远程调用失败了，也继续执行下边的保存操作，然后默认都是有库存的
            R r = wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            stockMap  = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常:原因{}",e);
        }
        //2.封装每个sku的信息为SkuEsModel这个模型的数据
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            //设置库存信息
            if (finalStockMap == null){//设置默认都是有库存的
                esModel.setHasStock(true);
            }else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            //TODO 热度评分，刚上架的商品，默认放0
            esModel.setHotScore(0L);
            //查出品牌和分类的名字信息
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());
            //设置检索属性
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());

        //将封装好的数据发给ES进行保存  远程调用riceshopping-search服务进行es的保存
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode()==0){
            //远程调用成功
            //TODO 成功上架之后，一定要修改当前spu的状态为已上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 重复调用？接口幂等性问题，因为上架服务是一个远程接口，这个远程接口调用失败了会不会自动的重试再来调用一次，也就是重试机制
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        //按照skuid找到spu的商品信息
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }


}